%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 6月 2022 17:18
%%%-------------------------------------------------------------------
-module(gate_router).
-author("Rain").
-include("obj.hrl").
-include("msg_id.hrl").

%% API
-export([route/2]).

route(?MSG_ID_LOGIN, Content) ->
    AccountName = proplists:get_value("account_name", Content),
    case AccountName of
        [_|_] ->
            UidValue = uid_svr:account_uid(AccountName),
            set_uid_value(UidValue),
            Msg = [{"uid", UidValue}],
            gate_util:send_sock_msg(?MSG_ID_LOGIN, Msg);
        _ ->
            pass
    end;

route(?MSG_ID_ENTER_GAME, Content) ->
    UidValue = proplists:get_value("uid", Content),
    case UidValue of
        UidValue when is_integer(UidValue) ->
            case get_uid_value() of
                UidValue ->
                    case erlang:whereis(?OBJ_SVR(UidValue)) of
                        undefined ->
                            {ok, _Pid} = obj_svr:start_obj_svr(UidValue, gate_util:get_process_sock());
                        _ ->
                            pass
                    end,
                    uid_svr:set_uid_route_pid(UidValue, self()),
                    gate_util:send_sock_msg(?MSG_ID_ENTER_GAME, []);
                _ ->
                    pass
            end;
        _ ->
            pass
    end;

route(MsgId, Content) ->
    case get_uid_value() of
        UidValue when is_integer(UidValue) ->
%%            io:format("RouteMsg ~p ~p ~n",[MsgId, BinMsg]),
            case erlang:whereis(?OBJ_SVR(UidValue)) of
                undefined ->
                    io:format("[ERROR] Uid(~p) is not enter game yet", [UidValue]);
                _ ->
                    ?OBJ_SVR(UidValue) ! {from_socket_msg, MsgId, Content}
            end;
        _ ->
            io:format("No RouteMsg"),
            pass
    end.

get_uid_value() ->
    get(uid_value).

set_uid_value(UidValue) ->
    put(uid_value, UidValue).